<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>拼多多打印(原demo数据)</title>
</head>

<body>
    <button onclick="getdd()">打印</button>
    <button onclick="getPrinterConfig()">获取打印机配置</button>
    <button onclick="getTaskStatus()">获取任务打印任务状态</button>
    <button onclick="getGlobalConfig()">获取全局配置(getGlobalConfig)</button>
    <button onclick="getAppInfo()"> 获取客户端版本信息(getAppInfo)</button>


    <h4>打印机列表:</h4>
    <div class="parent"></div>

    <h5>服务器返回的信息提示</h5>
    <div class="msg"></div>
</body>
<script>
    var socket;
    var getdd
    var jsonObject = {
		"ERPId": 303379400,
		"cmd": "print",
		"requestID": "90E06437",
		"task": {
			"documents": [
				{
					"contents": [
						{
							"addData": {
								"sender": {
									"address": {
										"city": "上海市",
										"detail": "陕西面馆",
										"district": "长宁区",
										"province": "上海市"
									},
									"mobile": "18377973853",
									"name": " B站号: chenxuyun",
									"phone": "523307"
								}, 
							},
							"encryptedData": "35803c72f596cb6aeeb2bf7249968965aa24ecba756f3e127d50c315d4e06cd5013899573a4d598eaf81a75556cca13c5ebab13723ddf1599dc5618f644baef72c78a170acd67233e1c271dafd8f34a43b70e1b4f16746a6b5febc112049fa2074f2cd3745a79d3ea0700cc8fafb9ef81ee5656ea541d26ce34eacad30c78739aa578c0ae34481dd9939b745aa9fb50009b2d5a09513225ee58664b5d5158d6780a9bab857c0c3c59faf514580324c56e6553fc44ab9c40fb1e57c0953fddae580c15ba45507af840bbcc7667832217064b5318bb445a3e23e6983e757fbab8856491f2320b5af8ac003273f288ed6b58ee96021691f05c533df5f755ed57693dffc60d9f6eb0bcb67fa04962df71333115198e90a6a5ea54d6a10da48ace14abbbe9273f14084925917d5c2a2a9bf9adfecfc17d0cd356418d6bbac201272be81e71a043755b98813bf6f86354dbc1992b4c8be5b459c793c73f28f2c6afd859509c303cd529c8e160270358314169a28e037e9c0def9f4950701de8978bc2874f67ffee2fc2f73bba159d5e8b26ffdda1258e8c862dbf829ca5f8be88e9182a5a9f32387cc964cb387726bdd56399dba8dfe503102088a4d1dadc07e97a464b094e31de84906a5f1c26813569ec3c510224a58fd5c49a172ad69217036078525c1428c54131aec25f02a83c1c6739fba45f1472aca26b55efc2268711076d79f395d17d0c49240ed00e34e8b3e077c633c922329c2a85de75bacdee7e21000fe9d2dc3aa0efed455985d5eb0eb4fa1b5265e26de3d807fd083b451e4c6668bb909832ec5df74d6a07e2c355c30736f1f0d3d7caaf35aa6ba4ac353b3eab8f66a381c4e0da904c23666479a0b1921d8ed19288cc0bf9925e2a86af0f9ee9967b7de61a296d23e47594ff6e745384da6b9cd5e55572e948d054113af793645bff8abc511d280e226cfe98d12e7c86f4f5aee4cf53fcea4425ad3cb1a99022361eb7e12102158f9f948dbee94dbf8495586d6d9a769c0647356c7f80186f4dca573b96476f1b88291329eeb29eebbb6a0",
							"signature": "PAPe5OYetWzKlZD3Wnvi4BPKI6CeCybLmYgzZioIw0XAs7dOdosozY9XXoYDf4cnByiza/JuDvoYQvgh+HYqaCNnJ0G1WnScQ7MSoWGkIcE6FBOxFhsbokLNX2ixiOQ4ERCuozajDsSYpDyOpqvDB4vT5AALyQjXAfnR8GyR/B4=",
							"templateUrl": "https://file-link.pinduoduo.com/yunda_std",
							"userid": "480261061",
							"ver": "3"
						},
						{
							"data": {
								"height": 240,
								"list": [
									{
										"fontSize": 30,
										"height": 45.68,
										"left": 2.08,
										"text": "[备注: B站号: chenxuyun]",
										"top": 2.08,
										"width": 413.52
									}
								],
								"waterdata": {
									"text": "微信公众号:软件聚导航",
									"fontSize":40
								},
								"width": 480
							},
							"templateURL": "http://pinduoduoimg.yangkeduo.com/logistics/2019-07-14/5d7e8b5969d954539fcfba3268bbeb3a.xml"
						}
					],
					"documentID": "5520010649869215"
				},
				
				
			],
			"notifyType": [
				"print"
			],
			"preview": false,
			"previewType": "image",
			"printer": "",
			"taskID": "03281843"
		},
		"version": "1.0"
	}


    var defaultPrinter
    var printerList
    // 保存打印任务taskID
    var taskIDArray = []
    // 全局配置请求ID,记录当前打印的 requestID 
    var requestIDGetGlobalConfig

    socket = new WebSocket('ws://127.0.0.1:5000');

    // 打开Socket
    socket.onopen = function (event) {
        getPrinters() //获取打印列表
        // 监听消息
        socket.onmessage = function (event) {
            // 获取拼多多返回的信息
            console.log('Client received a message', event);
            console.log('打印机列表', JSON.parse(event.data).printers)

            document.querySelector('.msg').innerText = JSON.stringify(event.data)

            if (JSON.parse(event.data).printers !== undefined) {
                printerList = JSON.parse(event.data).printers
                console.log('5555', printerList)
            }
            // JSON.parse 用来解析JSON字符串
            console.log("打印机" + JSON.parse(event.data).defaultPrinter)

            defaultPrinter = JSON.parse(event.data).defaultPrinter
            // defaultPrinter = 'OneNote for Windows 10'

            if (JSON.parse(event.data).status === 'success') {
                console.log("打印就绪..")
            }
            if (JSON.parse(event.data).taskStatus === 'printed') {
                console.log('出纸成功')
            }
            if (JSON.parse(event.data).taskStatus === 'failed') {
                // document.querySelector('.msg').innerText = JSON.stringify(event.data)
                console.log("打印失败!")
            }
            if (JSON.parse(event.data).taskStatus === 'canceled') {
                console.log("打印取消!")
            }
        };
        // 监听Socket的关闭
        socket.onclose = function (event) {
            console.log('Client notified socket has closed', event);
        };
    };

    // 测试:打印机列表展示
    setTimeout(() => {
        var parent = document.querySelector('.parent')
        for (i = 0; i < printerList.length; i++) {
            let h5 = document.createElement('h5')
            h5.innerText = printerList[i].name
            parent.appendChild(h5)
            h5.onclick = function () {
                defaultPrinter = this.innerText
                // alert("打印机名称:"+ defaultPrinter)
                doPrint(defaultPrinter)
            }
        }
    }, 500)



    getdd = function () {
        doPrint(defaultPrinter)
    }

    /***
     * 
     * 获取请求的UUID，指定长度和进制,如 
     * getUUID(8, 2)   //"01001010" 8 character (base=2)
     * getUUID(8, 10) // "47473046" 8 character ID (base=10)
     * getUUID(8, 16) // "098F4D35"。 8 character ID (base=16)
     *   
     */
    function getUUID(len, radix) {
        // 分割成字符串数组 0,1,2,3，.....
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');
        var uuid = [],
            i;
        radix = radix || chars.length;
        if (len) {
            for (i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
        } else {
            var r;
            uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
            uuid[14] = '4';
            for (i = 0; i < 36; i++) {
                if (!uuid[i]) {
                    r = 0 | Math.random() * 16;
                    uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
                }
            }
        }
        return uuid.join('');
    }

    // 构造request对象 
    function getRequestObject(cmd) {
        var request = new Object();
        // 必须:请求的ID,用于唯一标识每个请求，每个客户端保证生成唯一的ID
        request.requestID = getUUID(8, 16);
        //必须: 协议当前版本
        request.version = "1.0";
        //必须: 请求命令名称
        request.cmd = cmd;
        return request;
    }


    // 获取打印列表
    // "cmd": "getPrinters",
    // "requestID": "123458976",
    // "version": "1.0"
    function getPrinters() {
        var request = getRequestObject("getPrinters");
        if (socket.readyState === 1) {
            socket.send(JSON.stringify(request));
        }
    }

    // 获取打印机配置
    function getPrinterConfig() {
        var request = getRequestObject('getPrinterConfig')
        request.printer = defaultPrinter
        if (socket.readyState === 1) {
            socket.send(JSON.stringify(request));
        }
    }

    /**
     * 打印电子面单
     * printer 指定要使用那台打印机
     * waybillArray 要打印的电子面单的数组
     */
    function doPrint(printer) {
        var request = getRequestObject("print");
        request.task = new Object();
        request.task.taskID = getUUID(8, 10);

        // 把每次打印的任务 taskID 保存到 taskIDArray 数组
        taskIDArray.push(request.task.taskID)
        // 记录当前打印请求的ID
        requestIDGetGlobalConfig = request.task.taskID

        request.task.preview = false;
        request.task.printer = printer;
        request.task.documents = jsonObject.task.documents
        socket.send(JSON.stringify(request));
    }


    // 获取打印任务状态
    function getTaskStatus() {
        // 请求格式
        //         {
        //  "cmd": "getTaskStatus",
        //  "requestID": "123458976",
        //  "version": "1.0",
        //  "taskID": [
        //  "12311",
        //  "12312"
        //  ]
        // }
        var request = getRequestObject("getTaskStatus");
        request.taskID = taskIDArray
        socket.send(JSON.stringify(request));
    }

    // 获取全局配置(getGlobalConfig)
    function getGlobalConfig() {
        // 请求格式
        //  {
        //  "cmd": "getGlobalConfig",
        //  "requestID": "12345678901",
        //  "version": "1.0"
        // }
        var request = new Object()
        request.requestID = requestIDGetGlobalConfig
        request.cmd = "getGlobalConfig"
        request.version = "1.0"
        socket.send(JSON.stringify(request));
    }

    function getAppInfo() {
        //{
        //  "cmd": "getAppInfo",
        //  "requestID": "12345678901",
        //  "version": "1.0"
        // }
        var request = new Object()
        request.requestID = requestIDGetGlobalConfig
        request.cmd = "getAppInfo"
        request.version = "1.0"
        socket.send(JSON.stringify(request));

    }

</script>

</html>